﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
using RoadTeam.FineFile.Code;
using System.Xml;
using RoadTeam.FineFile.Model;
using System.Threading;
using System.Collections;

namespace RoadTeam.FineFile.GetPathInfo
{
    public partial class ReadExcel : Form
    {
        public ReadExcel()
        {
            InitializeComponent();
            #region 发布时需要注释掉
            //公司发布路径
            //SourceFilePath.Text = @"\\192.168.0.59\打包文件\发布网站\2014060601_新";

            #endregion


            TxtDateTimeNow.Text = DateTime.Now.ToString("yyyyMMddHHmmss");

            LoadTree();
            LoadProjectName();
        }
        /// <summary>
        /// 添加信息到listbox中 
        /// 滚动条在最下面
        /// </summary>
        /// <param name="Str"></param>
        private void ListBoxAddItem(String Str)
        {
            bool scroll = false;
            if (this.listBox1.TopIndex == this.listBox1.Items.Count - (int)(this.listBox1.Height / this.listBox1.ItemHeight))
                scroll = true; this.listBox1.Items.Add(Str);
            if (scroll) this.listBox1.TopIndex = this.listBox1.Items.Count - (int)(this.listBox1.Height / this.listBox1.ItemHeight);
        }

        #region 加载更新信息
        public void LoadTree()
        {
            String XmlPath = Application.StartupPath + @"\Xml";
            if (!Directory.Exists(XmlPath))
                Directory.CreateDirectory(XmlPath);

            String ExcelPath = Application.StartupPath + @"\Excel";
            if (!Directory.Exists(ExcelPath))
                Directory.CreateDirectory(ExcelPath);

            string XmlFile = XmlPath + @"\汇总更新.xml";

            if (!File.Exists(XmlFile)) return;

            UpdateInfo[] UpInfos = XmlOpera.GetUpdateInfoFromXml(XmlFile);
            // UpInfos = UpInfos.OrderBy(th => th.UpdateDate).OrderBy(th => th.UpdateContent).OrderBy(th => th.UpdatePerson).ToArray();
            UpInfos = UpInfos.OrderBy(th => th.UpdateDate).OrderBy(th => th.UpdatePerson).ToArray();

            UpdateFileTree.Nodes.Clear();
            UpdateFileTree.CheckBoxes = true;
            TreeNode tn;
            foreach (UpdateInfo item in UpInfos)
            {
                tn = new TreeNode();
                tn.Text = "[" + item.UpdateDate + "][" + item.UpdatePerson + "]" + item.UpdateContent;
                tn.Name = item.UpdateDate + "|" + item.UpdatePerson + "|" + item.UpdateContent;
                tn.Collapse();
                foreach (PathInfo pathinfo in item.Path)
                {
                    TreeNode Tn = new TreeNode();
                    Tn.Text = pathinfo.UrlPath;
                    tn.Nodes.Add(Tn);
                }
                UpdateFileTree.Nodes.Add(tn);
            }
        }
        #endregion

        #region 刷新XML更新信息
        private void UpdateXmlData_Click(object sender, EventArgs e)
        {
            String ExcelPath = Application.StartupPath + @"\Excel";
            if (!Directory.Exists(ExcelPath))
                Directory.CreateDirectory(ExcelPath);
            List<FileInfo> li = new List<FileInfo>();
            DirectoryInfo di = new DirectoryInfo(ExcelPath);
            List<String> LiUpdatePersons = new List<string>();
            foreach (FileInfo file in di.GetFiles())
            {
                li.Add(file); LiUpdatePersons.Add(file.Name.Replace(".xls", ""));
            }

            String XmlPath = Application.StartupPath + @"\Xml";
            if (!Directory.Exists(XmlPath))
                Directory.CreateDirectory(XmlPath);
            string XmlFile = XmlPath + @"\汇总更新.xml";

            if (!File.Exists(XmlFile))
                XmlOpera.CreateXmlFile(XmlFile, li);

            UpdateInfo[] UpdateInfos = GetFileInfo.GetUpdateInfo(li, XmlFile);
            //这里逻辑有问题
            //只要HashCode相同,整个树都不存在了!!
            //TODO:这里需要优先修改
            //XmlOpera.SetUpdateInfoToXml(XmlFile, UpdateInfos, LiUpdatePersons.ToArray());
            LoadTree();
            MessageBox.Show("XML数据更新成功");

        }
        #endregion

        #region 获取树节点中选中的路径

        private List<String> GetPath(ref  List<UpdateInfo> li_UpdateInfo)
        {
            List<String> li = new List<String>();
            li_UpdateInfo = new List<UpdateInfo>();
            //UpdateFileTree.Nodes
            String StrPathInfo = String.Empty;
            foreach (TreeNode item in UpdateFileTree.Nodes)
            {
                if (item.Checked)
                {
                    UpdateInfo ui = new UpdateInfo();
                    ui.UpdateDate = item.Name.Split('|')[0].ToString();
                    ui.UpdatePerson = item.Name.Split('|')[1].ToString();
                    ui.UpdateContent = item.Name.Split('|')[2].ToString();
                    List<PathInfo> temp = new List<PathInfo>();
                    foreach (TreeNode tn in item.Nodes)
                    {
                        PathInfo pi = new PathInfo();
                        pi.UrlPath = tn.Text;
                        temp.Add(pi);
                        StrPathInfo = tn.Text + "|" + ui.UpdateDate;
                        li.Add(StrPathInfo);
                    }
                    ui.Path = temp.ToArray();
                    li_UpdateInfo.Add(ui);
                }

            }
            return InSerTimeLineFile(li);
        }
        #region 强制更新更新时间轴文件
        public List<string> InSerTimeLineFile(List<string> li)
        {
            li.Add(@"UpdateLine\UpdateLine.htm|");
            li.Add(@"UpdateLine\ReadXmlHandler.ashx|");
            li.Add(@"UpdateLine\img\version_dot.png|");
            li.Add(@"UpdateLine\img\version_dot_alt.png|");
            li.Add(@"UpdateLine\UpdateLine.htm|");
            return li;
        }

        #endregion
        #endregion


        /// <summary>
        /// 保存项目配置信息
        /// </summary>
        public void SaveProJectInfo()
        {
            ProJectInfo proinfo = new ProJectInfo();
            proinfo.ProjectName = CmbProjectName.Text;

            proinfo.BackUpPath = BackUpPath.Text;
            proinfo.ProjectPath = ProjectFilePath.Text;


            String XmlPath = Application.StartupPath + @"\Xml";
            if (!Directory.Exists(XmlPath))
                Directory.CreateDirectory(XmlPath);
            string XmlFile = XmlPath + @"\ProjectInfos.xml";

            XmlOpera oprea = new XmlOpera();
            oprea.SaveProjectInfo(XmlFile, proinfo);


            if (!CmbProjectName.Items.Contains(CmbProjectName.Text))
                CmbProjectName.Items.Add(CmbProjectName.Text);
        }

        public bool Check(ref String Message)
        {
            if (String.IsNullOrEmpty(SelectRelease.Text))
            {
                Message = "当前没有选中任何打包方式";
                return false;
            }

            List<UpdateInfo> li_UpdateInfo = new List<UpdateInfo>();
            if (GetPath(ref li_UpdateInfo).Count == 0)
            {
                Message = "当前没有选中任何需要更新的文件"; return false;
            }
            //检验发布地址,更新文件地址,项目备份地址,项目名称
            if (String.IsNullOrEmpty(this.CmbProjectName.Text))
            {
                Message = "当前没有选择任何项目"; return false;
            }
            if (String.IsNullOrEmpty(this.SourceFilePath.Text))
            {
                Message = "网站发布地址不能为空"; return false;
            }
            if (String.IsNullOrEmpty(this.ProjectFilePath.Text))
            {
                Message = "项目文件地址不能为空"; return false;
            }

            if (String.IsNullOrEmpty(this.BackUpPath.Text))
            {
                Message = "项目备份地址不能为空"; return false;
            }
            return true;
        }


        public void LoadProjectName()
        {

            String XmlPath = Application.StartupPath + @"\Xml";
            if (!Directory.Exists(XmlPath))
                Directory.CreateDirectory(XmlPath);
            string XmlFile = XmlPath + @"\ProjectInfos.xml";

            if (!File.Exists(XmlFile)) return;

            XmlOpera opera = new XmlOpera();

            List<String> li = opera.GetProjectList(XmlFile);

            CmbProjectName.Items.Clear();

            foreach (String item in li)
            {
                CmbProjectName.Items.Add(item);
            }

        }


        private void Btn_PressFileThread_Click(object sender, EventArgs e)
        {
            String Message = String.Empty;
            if (!Check(ref Message))
            {
                MessageBox.Show(Message); return;
            }

            SaveProJectInfo();

            if (IsBackUp.Text == "备份")
                BackUpAndUpdate();
            else
                UpdateWithOutBackUp();
        }

        public void UpdateWithOutBackUp()
        {
            ThreadStart start = new ThreadStart(UpdateFile);
            Thread thread = new Thread(start);
            thread.Start();

        }

        private void BackUpAndUpdate()
        {
            //获取选中需要更新的问题,添加rar压缩文件备份原先文件夹中的文件
            //覆盖更新指定文件夹中的文件
            TxtDateTimeNow.Text = DateTime.Now.ToString("yyyyMMddHHmmss");
            toolStripMenuItem2.Text = "共0个文件";
            Btn_PressFileThread.Text = "备份扫描中....";
            Btn_PressFileThread.Enabled = false;
            FileCompress press = new FileCompress();
            press.CompressionLevel = 9;
            press.DirToZip = ProjectFilePath.Text;
            //String zipedFilePath = String.Empty;
            //zipedFilePath = String.IsNullOrEmpty(BackUpPath.Text) ? UpdateFilePath.Text : BackUpPath.Text;
            press.ZipedFile = BackUpPath.Text + "\\BackUp\\" + TxtDateTimeNow.Text + ".zip";

            this.progressBar1.Step = 1;
            RoadTeam.FineFile.Code.DelegateHander.ShowFileCountDelegate Showcbd = new DelegateHander.ShowFileCountDelegate(ShowFileCount);
            RoadTeam.FineFile.Code.DelegateHander.CallBackHashCountDelegate cbd = CallBackFileCount;
            press.ShowFileCountHander = Showcbd;

            //ListView显示初始化
            listBox1.Items.Clear();
            ListBoxAddItem("扫描需要备份的文件夹");
            //扫描文件夹中文件,后台线程准备中
            Thread thread = new Thread(press.getAllFiesByThread);
            thread.IsBackground = true;
            thread.Start(cbd);
        }

        /// <summary>
        /// 文件扫描完成
        /// </summary>
        /// <param name="HashCount"></param>
        /// <param name="Press"></param>
        private void CallBackFileCount(int HashCount, FileCompress Press)
        {
            //初始化进度条
            progressBar1.Maximum = HashCount;
            RoadTeam.FineFile.Code.DelegateHander.CallBackPressDelegate cbd = PressBarGrowth;
            RoadTeam.FineFile.Code.DelegateHander.CallBackPressFinishDelegate PressFinishcbd = new DelegateHander.CallBackPressFinishDelegate(PressFinish);
            Press.PressFinishHander = PressFinishcbd;
            Press.ZipDirByThread(cbd);
        }

        private void ShowFileCount(int Count, String FileName)
        {
            Btn_PressFileThread.Text = "扫描进行中....";
            toolStripMenuItem2.Text = "共" + Count + "个文件";
        }

        private void PressBarGrowth(String FileFullName)
        {
            if (progressBar1.Value == progressBar1.Maximum)
                progressBar1.Value = 0;
            else
                progressBar1.Value += progressBar1.Step;

            ListBoxAddItem("正在备份文件[" + FileFullName + "]");
        }

        private void PressFinish()
        {
            MessageBox.Show("压缩备份完成");
            ListBoxAddItem("备份完成");
            //获取文件更新
            UpdateFile();
        }

        public void UpdateFile()
        {
            Btn_PressFileThread.Text = "更新中....";
            Btn_PressFileThread.Enabled = false;

            ListBoxAddItem("准备更新文件");
            //  FileOpera fio = new FileOpera();
            ReFileOpera fio = new ReFileOpera();
            List<UpdateInfo> li_UpdateInfo = new List<UpdateInfo>();
            List<String> liPath = GetPath(ref li_UpdateInfo);


            String XmlPath = @Application.StartupPath + @"\\Xml\\汇总更新.xml";

            //查找相关联的更新文件
            //需要后人来重新调整算法,算法好像有问题
            //陈柯良 2014年9月16日9:47:44
            GetRelaInfo RelaInfo = new GetRelaInfo();
            liPath = RelaInfo.GetRelaPath(liPath, XmlPath, ref li_UpdateInfo);

            IGetPath FullPath;

            if (SelectRelease.Text == "新打包")
                FullPath = new GetNewFullPath();
            else
                FullPath = new GetOldFullPath();


            List<String> PathFileName = FullPath.GetFileFullPath(liPath, SourceFilePath.Text);
            progressBar1.Value = 0;
            progressBar1.Step = 1;
            progressBar1.Maximum = PathFileName.Count;
            for (int i = 0; i < PathFileName.Count; i++)
            {
                toolStripMenuItem2.Text = "正在复制第" + i + "个文件";
                ListBoxAddItem("正在更新文件[" + PathFileName[i] + "]");
                fio.CopyFile(SourceFilePath.Text, ProjectFilePath.Text, PathFileName[i]);
                progressBar1.Value += progressBar1.Step;
            }

            //输出对应的更新XML数据
            ListBoxAddItem("准备更新" + ProjectFilePath.Text + "路径下的XML汇总文档,文件名为[UpdateSummary.xml]");
            XmlOpera opera = new XmlOpera();
            opera.PrintUpdateSummary(ProjectFilePath.Text + @"\UpdateSummary.xml", li_UpdateInfo, TxtDateTimeNow.Text);
            ListBoxAddItem("XML汇总文档更新完毕");

            //输出对应的TXT更新问题
            ListBoxAddItem("准备生成" + BackUpPath.Text + "路径下的本次更新汇总文档,文件名为[" + TxtDateTimeNow.Text + ".txt]");
            ReadWrite rw = new ReadWrite();
            rw.PrintUpdateSummary(BackUpPath.Text + "\\UpdateInfo\\" + TxtDateTimeNow.Text + ".txt", li_UpdateInfo);
            ListBoxAddItem("本次更新汇总文档更新完毕");


            MessageBox.Show("文件更新完成,抓紧时间去试试");
            ListBoxAddItem("本次更新完毕");

            Btn_PressFileThread.Text = "一键更新";
            Btn_PressFileThread.Enabled = true;

            //重新加载项目信息
            LoadProjectName();
            //线程回收
            Thread.CurrentThread.Abort();
        }

        private void ReadExcel_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            FrmProjectPath Frm = new FrmProjectPath();
            Frm.ShowDialog();
        }

        private void CmbProjectName_SelectedIndexChanged(object sender, EventArgs e)
        {
            String XmlPath = Application.StartupPath + @"\Xml";
            if (!Directory.Exists(XmlPath))
                Directory.CreateDirectory(XmlPath);
            string XmlFile = XmlPath + @"\ProjectInfos.xml";

            if (!File.Exists(XmlFile)) return;

            XmlOpera opera = new XmlOpera();
            ProJectInfo proinfo = opera.GetProInfoByName(XmlFile, CmbProjectName.Text);
            this.BackUpPath.Text = proinfo.BackUpPath;
            this.ProjectFilePath.Text = proinfo.ProjectPath;
            CmbProjectName.Text = proinfo.ProjectName;

        }
    }
}
